/*
 * con_state.cpp
 *
 *  Created on: Sep 17, 2010
 *      Author: khanton
 */

#include <string.h>

#include "con_state.h"

con_state::con_state() :
	have_active_connection_(false),
	last_access_time_(0),
	
	rtc_hour_(0),
	rtc_min_(0),
	rtc_sec_(0),
	rtc_day_(0),
	rtc_month_(0),
	rtc_year_(0),
	rtc_day_of_week_(0),
	
	flash_status_(0),
	job_mode_(0),
	
	current_program_(0),
	current_phase_(0),
	
	fault_type_(0),
	fault_red_(0),
	fault_yellow_(0),
	fault_green_(0),
	
	no_programm_(0),
	phase_time_(0)
{
}

con_state::~con_state() 
{
}

#define BCD(a) (a & 0x0f) + (((a & 0xf0) >> 4) * 10)

void con_state::operator = (const con_state::status_packet_t &_state)
{
	time(&last_access_time_);
	
	rtc_hour_ = _state.rtc_hour_;
	rtc_min_ = _state.rtc_min_;
	rtc_sec_ = _state.rtc_sec_;
	rtc_day_ = _state.rtc_day_;
	rtc_month_ = _state.rtc_month_;
	rtc_year_ = _state.rtc_year_;
	rtc_day_of_week_ = _state.rtc_day_of_week_;
	
	flash_status_ = _state.flash_status_;
	job_mode_ = _state.job_mode_;
	
	current_program_ = _state.current_program_;
	current_phase_ = _state.current_phase_;
	
	fault_type_ = _state.fault_type_;
	fault_red_ = _state.fault_red_;
	fault_yellow_ = _state.fault_yellow_;
	fault_green_ = _state.fault_green_;
	
	no_programm_ = _state.no_programm_;
	phase_time_ = _state.phase_time_;
	
}

void con_state::setup_packet(con_state::status_packet_t &_state)
{
	memset(&_state, 0, sizeof(_state));
	_state.sign_ = 0x20;
	_state.rtc_hour_ = rtc_hour_;
	_state.rtc_min_ = rtc_min_;
	_state.rtc_sec_ = rtc_sec_;
	_state.rtc_day_ = rtc_day_;
	_state.rtc_month_ = rtc_month_;
	_state.rtc_year_ = rtc_year_;
	_state.rtc_day_of_week_ = rtc_day_of_week_;
	
	_state.flash_status_ = flash_status_ ;
	_state.job_mode_ = job_mode_;
	
	_state.current_program_ = current_program_;
	 _state.current_phase_ = current_phase_;
	
	_state.fault_type_ = fault_type_;
	_state.fault_red_ = fault_red_;
	_state.fault_yellow_ = fault_yellow_;
	_state.fault_green_ = fault_green_;
	
	_state.no_programm_ = no_programm_;
	_state.phase_time_ = phase_time_;

}

boost::posix_time::ptime con_state::as_local_time() const
{
/*  struct tm itime;
  
  memset(&itime, 0, sizeof(itime));
  
  itime.tm_sec = BCD(rtc_sec_);
  itime.tm_min = BCD(rtc_min_);
  itime.tm_hour = BCD(rtc_hour_);
  itime.tm_mday = BCD(rtc_day_);
  itime.tm_mon = BCD(rtc_month_) - 1;
  itime.tm_year = BCD(rtc_year_) + 100;*/
  
  return boost::posix_time::ptime(
			boost::gregorian::date(BCD(rtc_year_) + 2000, BCD(rtc_month_), BCD(rtc_day_)),
			  boost::posix_time::hours(BCD(rtc_hour_)) +
			  boost::posix_time::minutes(BCD(rtc_min_)) +
			  boost::posix_time::seconds(BCD(rtc_sec_))
			);

}
